package cn.com.connected.common.aop;

import cn.com.connected.base.cache.CacheService;
import cn.com.connected.base.exception.BusinessException;
import cn.com.connected.base.exception.ErrorCode;
import cn.com.connected.base.utils.StringTools;
import cn.com.connected.common.config.CurrentData;
import cn.com.connected.common.emnus.CacheKey;
import cn.com.connected.common.utils.JwtUtil;
import cn.com.connected.service.MemberService;
import cn.com.connected.vo.MemberVo;
import cn.com.connected.vo.base.TokenVO;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import static cn.com.connected.common.emnus.HttpParams.AUTHORIAZTION;

/**
 * Created by shaomingsheng on 2017/10/20.
 */
@Aspect
@Component
@Slf4j
@Order(1)
public class LoginAOP {
  @Resource
  private CacheService cacheService;

  @Resource
  private MemberService memberService;

  @Resource
  private JwtUtil jwtUtil;

  @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
  public void requestMapping(){}

  @Pointcut("execution(* cn.com.connected.controller.open..*.*(..))")
  public void openPackage() {}

  @Pointcut("@annotation(cn.com.connected.base.annotations.OpenApi)")
  public void OpenApi() {}

  @Pointcut("@annotation(cn.com.connected.base.annotations.CheckApi)")
  public void CheckApi() {}

  @Pointcut(value = "execution(* cn.com.connected.controller..*.*(..))")
  public void connectedPackage() {}


  @Order(1)
  @Around("connectedPackage() && requestMapping() && !openPackage() && !OpenApi() || CheckApi()")
  public Object handlerLogin(ProceedingJoinPoint pjp)  throws Throwable{

    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    String auth = request.getHeader(AUTHORIAZTION);
    if (auth == null){
      throw new BusinessException(ErrorCode.LOGIN_TIMEOUT);
    }
    TokenVO tokenVO = jwtUtil.parseJwtToBean(auth);
    String token = cacheService.getObject(StringTools.format(CacheKey.LOGIN_TOKEN,tokenVO.getId()));
    if (token == null){
      throw new BusinessException(ErrorCode.LOGIN_TIMEOUT);
    }
    if (!auth.equals(token)){
      throw new BusinessException(ErrorCode.LOGIN_OTHER_ADDRESS);
    }
    MemberVo memberVo = memberService.memberInfoById(tokenVO.getId());

    CurrentData.setUser(memberVo);

    Object result =  pjp.proceed();
    return result;


  }


}